import React, { Component } from 'react';
import { StyleSheet, Text, View, ScrollView, ActivityIndicator, PixelRatio, TextInput, DeviceEventEmitter, Modal, Keyboard } from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { cStyles } from '../RequirementStyle.js';
import { Common } from '../../../component/common/Common.js'
import { LargeBtn } from '../component/Component.js';
import { ApprovalView, RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../utils/toast'

const scale = GLOBAL.SCALE;

const showConfig = {
	rejectError: false,
	handleError: true,
}
const sendData = {};

export class RequirementPlanApprovalDetailPage extends Component {

	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '客户需求审批',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		};
	};

	constructor(props) {
		super(props);
		this.state = {
			loading: true,
			demand: {},
			resultModalVisible: false,
			refuseModalVisible: false,
			quantityModalVisible: false,
			keyboard: false,
			pageStatus: {
				status: 'loading'
			},
		}

		this._fetchApproval = this._fetchApproval.bind(this);
		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);
	}

	async componentWillMount () {
		if (this.props.navigation.state.params && this.props.navigation.state.params.paramsData.demandId) {
			sendData.demandId = this.props.navigation.state.params.paramsData.demandId;
			const demand = await HTTP.POST(API_GENERATE(API.DAMAND_DETAIL), {
				demandId: this.props.navigation.state.params.paramsData.demandId
			}, showConfig);
			if (demand) {
				this.setState({
					pageStatus: {
						status: 'data',
					},
					demand,
				});
				sendData.suggestQuantity = demand.suggestQuantity;
			} else {
				this.setState({
					pageStatus: {
						status: 'empty'
					}
				});
			}
		}

		this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
		this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));

	}

	async _fetchApproval () {
		const responseData = await HTTP.POST(API_GENERATE(API.DAMAND_APPROVAL), sendData);
		if (responseData) {
			const msg = (sendData.status == 'UNPASS') ? '驳回成功' : '审批成功';
			ToastUtil.showSuccess(msg);
			this.timer = setTimeout(() => {
				this._goBack();
			}, 800)
		}
	}

	// 返回上一个页面
	_goBack = () => {
		DeviceEventEmitter.emit('requirementListener');
		this.props.navigation.navigate('HomePage');
	}

	render () {
		const { loading, demand, refuseModalVisible, pageStatus } = this.state;
		let demandLogisticsView = null;
		if (demand && demand.demandLogisticsVOS && demand.demandLogisticsVOS.length) {
			demandLogisticsView = demand.demandLogisticsVOS.map((logistical, i) => {
				const { deliveryBeginDate, deliveryEndDate, quantity, uom, address } = logistical;
				return (
					<View>
						<Row left={'提货时间'} right={`${this._getDateStr(deliveryBeginDate)}-${this._getDateStr(deliveryEndDate)}`} />
						<Row left={'数量'} right={quantity || ''} />
						<Row left={'单位'} right={uom || ''} />
						{/*<Row left={'提货地点'} right={address || ''} />*/}
					</View>
				);
			});
		} else {
			demandLogisticsView = <View>
				<Text style={cStyles.text}>无</Text>
			</View>
		}

		let { approval, status, } = demand;
		const largeBtn = (status == 'UNPASS') ? null : null;// <LargeBtn onPress={this._didPressLargeBtn} text={'填写客户确认量'} />
		approval = Number(approval);
		//审批按钮
		const approvalView = this.getApprovalView();
		const loadedCell = loading ? <View style={styles.loadedCell}>
			<ActivityIndicator
				animating={true}
				color={'#fff'}
				size="small"
			/>
		</View> : null;

		const quantityModal = this.getQuantityModal();
		return (
			<View style={styles.container}>
				{
					pageStatus.status === 'data' ?
						(<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>
							<View style={styles.pane}>
								<View style={styles.paneWrap}>
									<View style={styles.titleView}>
										<Text style={cStyles.text}>基础信息</Text>
									</View>
									<Row left={'需求类型'} right={demand.demandTypeName} />
									<Row left={'计划月份'} right={demand.month} />
									<Row left={'客户名称'} right={demand.companyName} />
									<Row left={'商品名称'} right={demand.goodsName} />
									<Row left={'数量'} right={demand.quantity} />
									<Row left={'单位'} right={demand.uom} />
									<Row left={'联系人'} right={demand.linkName} />
									<Row left={'业务员'} right={demand.staffName} />
									<Row left={'交货方式'} right={demand.deliveryMethod} />
									<View style={styles.titleView}>
										<Text style={cStyles.text}>备注</Text>
									</View>
									<Text style={cStyles.text}>{demand.remark ? demand.remark : '无'}</Text>
								</View>
							</View>
							<View style={styles.pane}>
								<View style={styles.paneWrap}>
									<View style={styles.titleView}>
										<Text style={cStyles.text}>物流信息</Text>
									</View>
									{demandLogisticsView}
								</View>
							</View>
						</ScrollView>)
						: (<PageStatusIndex {...pageStatus} />)   //页面加载状态
				}

				{approvalView}
				{largeBtn}
				<RefuseModal visible={refuseModalVisible} btnPress={async (auditRemark) => {
					sendData.status = 'UNPASS';
					sendData.auditRemark = auditRemark;
					delete sendData.suggestQuantity;
					await this._fetchApproval();
				}} bgPress={() => {
					this.setState({
						refuseModalVisible: false,
					});
				}} />
				{quantityModal}
			</View>
		);
	}

	getApprovalView () {
		const { demand } = this.state;
		const { status } = demand;
		const quantity = "" + demand.quantity;
		return (status && status.indexOf('PASS') == -1) ? (
			<View style={{ backgroundColor: '#fff', }}>
				<View style={styles.quantityView}>
					<Text style={cStyles.text}>经营计划部建议量</Text>
					<TextInput
						ref="quantityInput"
						style={[cStyles.textInput, styles.quantityInput]}
						underlineColorAndroid='transparent'
						placeholder={"请输入"}
						placeholderTextColor="#999"
						maxLength={30}
						editable={true}
						defaultValue={quantity || ''}
						keyboardType="numeric"
						onChangeText={(txt) => { sendData.suggestQuantity = txt }}
					/>
				</View>
				<ApprovalView agreePress={async () => {
					sendData.status = 'PASS';
					await this._fetchApproval();
				}} refusePress={() => {
					this.setState({
						refuseModalVisible: true
					})
				}} />
			</View>
		) : null;
	}

	componentWillUnmount () {
		try {
			this.keyboardDidShowListener.remove();
			this.keyboardDidHideListener.remove();
		} catch (error) {
			console.log(error);
		}

	}

	_getDateStr (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "年" + (m < 10 ? "0" + m : m) + "月" + (d < 10 ? "0" + d : d) + "日";
			return dateStr;
		} else {
			return '';
		}
	}

	componentDidMount () { }

	_keyboardDidShow () {
		this.setState({
			keyboard: true,
		});
	}

	_keyboardDidHide () {
		this.setState({
			keyboard: false,
		});
	}

	getQuantityModal () {
		const { quantityModalVisible, keyboard } = this.state;
		return (
			<Modal animationType={"fade"}
				transparent={true}
				animationType="slide"
				visible={quantityModalVisible}
				onRequestClose={() => { }}>
				<View style={styles.containerModal}>
					<View style={styles.quantityBox}>
						<View style={styles.quantityBoxTitle}>
							<Text style={cStyles.text}>客户确认量</Text>
						</View>
						<LargeBtn onPress={() => { }} text={'提交'} />
					</View>
				</View>
			</Modal>
		)
	}

	/**
	* 点击底部按钮
	*/
	async _didPressLargeBtn () {
		this.setState({
			quantityModalVisible: true,
		});
	}

}

/**
 * 行
 * @param {object} props left, right
 */
function Row (props) {
	const { left, right } = props;
	return (
		<View style={styles.row}>
			<Text style={cStyles.text}>{left}</Text>
			<Text style={cStyles.text}>{right}</Text>
		</View>
	);
}

const styles = StyleSheet.create({
	quantityInput: {
		marginLeft: 30 * scale,
		alignSelf: 'center'
	},
	quantityView: {
		flexDirection: 'row',
		height: 50 * scale,
		alignItems: 'center',
		paddingLeft: 14 * scale,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		justifyContent: 'flex-end'
	},
	quantityBox: {
		width: 375 * scale,
		height: 282 * scale,
		backgroundColor: '#fff',
	},
	quantityBoxTitle: {
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		width: 375 * scale,
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	scrollView: {

	},
	container: {
		flex: 1,
		backgroundColor: '#F6F6F6',
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
		position: 'absolute',
		left: 140 * scale,
		top: 150 * scale,
	},
	pane: {
		backgroundColor: '#fff',
		alignItems: 'center',
		marginTop: 12 * scale,
		paddingBottom: 42 * scale,
	},
	paneWrap: {
		width: 345 * scale,
	},
	row: {
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		flexDirection: 'row',
		height: 42 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	text: {
		fontSize: 13 * scale,
		color: '#404040'
	},
	titleView: {
		height: 40 * scale,
		justifyContent: 'center',
	}
})